package cn.com.idmy.cloud.advice;

import cn.com.idmy.base.exception.BizException;
import cn.com.idmy.base.model.Out;
import cn.com.idmy.base.util.AppUtil;
import cn.com.idmy.cloud.exception.CloudException;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.core.text.StrUtil;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class CloudGlobalResponseHandler extends GlobalResponseHandler {
    @NotNull
    @ExceptionHandler(FeignException.class)
    public ResponseEntity<Out> exceptionHandler(@NotNull FeignException e) {
        var httpStatus = HttpStatus.resolve(e.status());
        if (httpStatus == null) {
            httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        }
        log.error(FeignException.class.getSimpleName(), e);
        return new ResponseEntity<>(Out.err().msg(e.getMessage()), httpStatus);
    }

    @ExceptionHandler(CloudException.class)
    public ResponseEntity<Out> handler(@NotNull CloudException e) {
        var status = HttpStatus.resolve(e.code());
        if (status == null) {
            status = HttpStatus.INTERNAL_SERVER_ERROR;
        }
        var msg = e.getMessage();
        if (StrUtil.isNotBlank(msg)) {
            msg = msg.replace(BizException.class.getSimpleName() + ": ", "");
        }
        if (AppUtil.isLocal()) {
            log.error(msg);
        } else {
            log.error(msg, e);
        }
        return new ResponseEntity<>(Out.err().msg(msg).code(e.code()), status);
    }
}
